package com.fsbm.ctech.maxis.ebpsbackend;

import com.checkfree.isolutions.persist.PersistServer;
import com.checkfree.isolutions.property.Properties;
import com.checkfree.isolutions.property.PropertiesConfig;
import com.checkfree.isolutions.utility.*;

/**
 * Module Id    :
 * Description  :  The <code>InsertStmtRunExt</code> class insert Statement Run details in the StatementRunExt table.
 *
 * @version 1.00
 * @author  Jason R. Sarmiento
 *
 * @param stmtDtlFile  The Statement Run detail file
 *
 * @return 1 for success and 0 for failure
 * @exception
 *
 * @Change History
 * @--------------
 * @Author      :
 * @Date        :
 * @Description :
 */


public class InsertStmtRunExt {

    private static String stmtDtlFile = new String();
    public static String jdbcDriver = new String();
    public static String jdbcDataSource = new String();
    public static String username = new String();
    public static String password = new String();

    /*
    public InsertStmtRunExt()
    {
    }
     */

    public static boolean parseArguments(String[] args)
    {
        boolean flag = true;
        for (int i = 0; i < args.length; i++)
        {
            String temp = args[i];
            String parm = new String();
            String value = new String();
            int pos = temp.indexOf('=');

            if ((temp.compareTo("-?") == 0) || (pos < 0) || (temp.compareToIgnoreCase("-h") == 0))
            {
                flag = false;
                break;
            }

            parm  = temp.substring(0, pos);
            value = temp.substring(pos+1, temp.length());

            if (parm.compareToIgnoreCase("-stmtDtlFile") == 0)
                stmtDtlFile = value;
            //else {
            //    flag = false;
            //    break;
            //}
        }

        if (stmtDtlFile.trim().length() <= 0)
            flag = false;

        if (flag == false)
            programUsage();

        return (flag);
    }

    public static void getDbConfig()
    {
        try
        {
            Properties appCfg = PropertiesConfig.getApplicationSettings();
            if (appCfg.hasProperty("JDBCDriverName") == false)
                throw new IllegalArgumentException("JDBC Driver not specified!");
            else
                jdbcDriver = appCfg.getProperty("JDBCDriverName");

            if (appCfg.hasProperty("JDBCDataSourceName") == false)
                throw new IllegalArgumentException("JDBC Data Source not specified!");
            else
                jdbcDataSource = appCfg.getProperty("JDBCDataSourceName");

            if (appCfg.hasProperty("DataBaseUserid") == false)
                throw new IllegalArgumentException("Database userid not specified!");
            else
                username = appCfg.getProperty("DataBaseUserid");

            if (appCfg.hasProperty("DataBasePassword") == false)
                throw new IllegalArgumentException("Database password not specified!");
            else
                password = appCfg.getProperty("DataBasePassword");
        }
        catch (CFiError cfi)
        {
            System.out.println("CFiError " + cfi);
        }
    }

    public static void programUsage()
    {
        System.out.println("InsertStmtRunExt - Insert Statement Run details in the StatementRunExt table.");
        System.out.println("FSBM CTech Sdn Bhd (427095)-M");
        System.out.println("Copyright (C) FSBM CTech. All rights reserved.\n");
        System.out.println("Program Usage : InsertStmtRunExt -stmtDtlFile=<filename>");
        System.out.println("Where:");
        System.out.println("\tstmtDtlFile   - Statement Run detail file (required)");
        System.out.println("\t-h            - to display this usage");
        System.out.println("\t-?            - to display this usage");
    }

    public static void main (String[] args){

        if (parseArguments(args) == true){
            runProg();
        }
    }

    public static void setStmtDtlFile(String str)
    {
        stmtDtlFile = str;
    }

    public static String getStmtDtlFile()
    {
        return (stmtDtlFile);
    }

    public synchronized static void runProg()
    {
        try{
            // always activate before anything else. This app doesn't supply an appname,
            // so it uses the default common.cfg
            PersistServer.activate();
            PersistServer.beginTransaction();

            // get database configuration
            getDbConfig();

            // load JDBC driver
            Class.forName(jdbcDriver);
            java.sql.Connection connection = java.sql.DriverManager.getConnection(jdbcDataSource, username, password);
            java.sql.PreparedStatement pstmtInsert=null;

			String insertSql="INSERT INTO statementrunext (STATEMENTRUNID, MAILMETHOD, PRINTVENDOR) VALUES (?,?,?)";
            pstmtInsert = connection.prepareStatement(insertSql);

			//java.sql.Statement statement = connection.createStatement();

            // read stmtDtlFile
            String buffer = new String();
            java.io.BufferedReader in = new java.io.BufferedReader(new java.io.FileReader(stmtDtlFile));
            while((buffer = in.readLine()) != null)
            {
                java.util.StringTokenizer strTokenizer = new java.util.StringTokenizer(buffer, ",");
                String stmtRunId = strTokenizer.nextToken();
                String mailType = strTokenizer.nextToken();
                String printVendor = strTokenizer.nextToken();

                pstmtInsert.setString(1, stmtRunId);
				pstmtInsert.setString(2, mailType);
				pstmtInsert.setString(3, printVendor);

                pstmtInsert.executeUpdate();

				/*String strInsert = "INSERT INTO statementrunext VALUES ('" +
                stmtRunId + "','" + mailType + "','" + printVendor + "')";
                int result = statement.executeUpdate(strInsert);*/

            }
            in.close();

			connection.commit();
            pstmtInsert.close();
            connection.close();
            PersistServer.commitTransaction();
        }
        catch (IllegalArgumentException iae)
        {
            System.err.println("Error in configuration: " + iae);
        }
        catch (ClassNotFoundException cnfe)
        {
            System.err.println("Error loading driver: " + cnfe.getClass() + cnfe.getMessage());
        }
        catch (java.sql.SQLException sqle)
        {
            System.err.println("Error connecting: " + sqle);
        }
        catch (Exception ex)
        {
            System.out.println("-- EXCEPTION: " + ex.getClass() + " " + ex.getMessage());
        }
        catch (Throwable t)
        {
            System.out.println("-- EXCEPTION: " + t.getClass() + " " + t.getMessage());
        }
        finally
        {
            if (PersistServer.transactionIsActive())
            {
                try{
                    PersistServer.rollbackTransaction();
                }
                catch (Exception e)
                {
                    // ignore
                }
            }
            // clean up with deactivate
            PersistServer.deactivate(true);
        }
    }
}